import mysql.connector
from mysql.connector import Error
from datetime import datetime
import cv2 as cv#importing package
import os
import sys
import math
import numpy as np
import itertools
from matplotlib import pyplot as plt

#ENUMS
CAMERA_IMAGE_INDEX = 0 #FOR WHICH VIDEO CAMERA CONNECTED. 0=webcam, 1 = external cam
CAMERA_FRAMERATE_SLOWDOWN = 30 #THE HIGHER NUMBER, THE SLOWER THE FPS. 0 = NO SLOWDOWN, 30 = 1fps

'''
Control class 
Initialises all assets, such as database connection, camera connection, and DL model
manages logical flow of program
'''
class Control():
    def __init__(self) -> None:
        self.setup()
        self.main()
        
    def setup(self):
        #call database setup
        self.db = Database()
        self.camera = Camera()
        self.model = ImageRecognition()
    
    def handle_query(self):
        # datetime object containing current date and time
        now = datetime.now()
        
        dt_string = now.strftime("%Y-%m-%d %H:%M:%S")

        mySql_Create_Table_Query = """INSERT INTO rubbishlocation (cameraid, latitude, longitude, time)
            values ('1','666','777','{}')""".format(dt_string)
        
        self.db.insert(mySql_Create_Table_Query)
        
        self.db.close_connection()

    '''Main runs the camera
    '''
    def main(self):
        # call camera
        #self.handle_query()
        self.camera.runcamera(self.model)

class Database():
    def __init__(self)->None:
        self.setup_connection()
    
    def insert(self, query):
        #using connection, create temporary cursor
       
        self.cursor.execute(query)
        self.connection.commit()
        print(self.cursor.rowcount, "Record inserted successfully into table")
        result = self.cursor.fetchall()

    def setup_connection(self):
        try:
            connection = mysql.connector.connect(host='localhost',
                                                database='greenstreets',
                                                user='CAMERA',
                                                password='password')
            self.connection = connection
            self.cursor = connection.cursor()
        except mysql.connector.Error as error:
            print("Failed to create table in MySQL: {}".format(error))
    
    def close_connection(self):
        if self.connection.is_connected():
            self.cursor.close()
            self.connection.close()
            print("MySQL connection is closed")

class Camera():
    def init(self) -> None:
        self.setup()

    def setup(self):
        pass
    
    '''
    runcamera starts video capture
    read image from video
    slows down framerate of refresh
    sends each image to the model to be processed.
    
    '''
    def runcamera(self, model):
        self.cap = cv.VideoCapture(CAMERA_IMAGE_INDEX, cv.CAP_DSHOW)
        
        while(self.cap.isOpened()):#while video is connected
            fpscounter = 0
            while True:
                ret, img = self.cap.read()#read from image
                if (ret): 
                    if fpscounter == CAMERA_FRAMERATE_SLOWDOWN: 
                        # reset counter, display image
                        fpscounter = 0
                        #pass image to model
                        model.processImage(img)
                        cv.imshow('img', img)
                    else:#non frame rate hit
                        fpscounter += 1 
                    
                    if cv.waitKey(30) & 0xff == ord('q'):
                        break
            self.cap.release()
            cv.destroyAllWindows()
        else:
            print("Alert ! Camera disconnected")

class ImageRecognition():
    def init(self):
        pass

    def setup(self):
        pass

    def processImage(self, img):
        print("GOT IMAGE")

app = Control()
